package org.ams.account.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.ams.account.dao.AccountDao;
import org.ams.account.entity.Account;
import org.ams.account.service.AccountService;
import org.ams.common.util.Common;
import org.ams.role.dao.RoleDao;
import org.ams.role.entity.RoleAccount;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountSerivceImpl implements AccountService {

	@Resource
	private AccountDao accountDao;
	
	@Resource
	private RoleDao roleDao;

	@Override
	public List<Account> queryAccountListByPage(Map<String, Object> params) {
		return accountDao.queryAccountList(params);
	}

	@Override
	public Account queryAccountByAccountName(String accountName) {
		return accountDao.queryAccountByAccountName(accountName);
	}

	@Override
	public Integer deleteAccountsByIds(Map<String, Object> params) {
		Integer returnRows = accountDao.deleteAccountsByIds(params);
		if(0 < returnRows){
			//删除对应的角色信息
			roleDao.deleteRoleAccountByAccountIds(params);
		}
		return returnRows;
	}

	@Override
	public Account queryAccountByAccountId(Integer accountId) {
		return accountDao.queryAccountByAccountId(accountId);
	}

	@Override
	public Integer updateAccount(Account account) {
		Integer returnRows = accountDao.updateAccount(account);
		saveRoleAccount(account);
		return returnRows;
	}

	@Override
	public Integer saveAccount(Account account) {
		Integer returnRows = accountDao.saveAccount(account);
		saveRoleAccount(account);
		return returnRows;
	}
	
	private void saveRoleAccount(Account account){
		Map<String, Object> params = new HashMap<String, Object>();
		Integer accountId = account.getAccountId();
		Integer[] roles = account.getRoles();
		if(null != roles) {
			List<Integer> idList = Common.createIdList(accountId + ",", ",");
			params.put("idList", idList);
			roleDao.deleteRoleAccountByAccountIds(params);
			for (Integer roleId : roles) {
				params.clear();
				params.put("accountId", accountId);
				params.put("roleId", roleId);
				List<RoleAccount> roleAccountList = roleDao.queryRoleAccountListByMap(params);
				if(null == roleAccountList || roleAccountList.isEmpty()){
					RoleAccount ra = new RoleAccount();
					ra.setAccountId(accountId);
					ra.setRoleId(roleId);
					ra.setCreateTime(new Date());
					roleDao.saveRoleAccount(ra);
				}
			}
		}
	}
	
}
